/**
 * 
 */
package idao.engine;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;

import idao.ConnectionManager;
import idao.DaoRuntimeException;

/**
 * @author Hodge
 *
 */
abstract class DaoProxy
{
    protected DaoProxy()
    {
        // for subclass
    }

    protected Object invokeMethod(Method method, Object[] args, ConnectionManager cm)
    {
        DaoMethod daoMethod = DaoMethod.getDaoMethod(method);
        Connection txCon = TxManager.getTxConnection(cm);
        try {
            return daoMethod.invoke(txCon, args);
        } finally {
            cm.returnConnection(txCon);
        }
    }

    protected RuntimeException transfromException(Throwable t, Class<?> dao)
    {
        if (t instanceof InvocationTargetException) {
            return transfromException(((InvocationTargetException)t).getTargetException(), dao);
        } 
        if (t instanceof RuntimeException) {
            return (RuntimeException)t;
        }
        return new DaoRuntimeException("Failed to create new proxy of [" + dao + "].", t);
    }
}
